#include "regist.h"
#include "ui_regist.h"

Regist::Regist(QList<User *> users, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Regist)
{
    ui->setupUi(this);
    this->users = users;

    this->initScene(); //初始化窗口
}

Regist::~Regist()
{
    delete ui;
}

//获取所有用户
void Regist::getAllUsers(){
    this->users.clear(); //清空链表
    //读取文件
    QFile file ("./user.txt");
    file.open(QIODevice::ReadOnly| QIODevice::Text );
    QByteArray t=file.readAll();
    QString alltext=QString(t);
    QStringList list=alltext.split("\n");
    for (int i=0; i<list.size() ;i++ ) {
        QStringList temp=list[i].split(" ");
        if(temp.size()>3){
            this->users.append(new User(temp[0],temp[1], temp[2], temp[3]));
        }
    }
    file.close();
    //往user中临时存数据
    //users.append(new User("123123","123123"));
}

void Regist::on_regist_clicked()
{
    //获取文本框值
    QString username=ui->name->text();
    QString password=ui->pwd->text();
    QString score = QString::number(0);
    QString nickName = ui->nickName->text();

    //判断输入用户名是否重复
    this->getAllUsers();
    int flag=0;
    for(int i=0;i<users.size();i++){
        if(QString::compare(username,users.at(i)->userName)==0
               ){ //如果重复.
            flag=1;

            break;
        }
    }

    //根据标志跳转窗口
    if(flag==1){
            QMessageBox::warning(NULL,GAME_NAME,"该用户名已被使用！",QMessageBox::Yes);
        }else{
            if(this->isPwdSame()){ //判断两次输入的密码是否一致
                //获取不重复的端口
                while(1){
                    this->regiUser = new User(username, password, score, nickName);
                    if(!this->isPostExist(this->regiUser->post)){ //如果端口不存在
                        break;
                    }
                }
                QMessageBox::information(NULL,GAME_NAME,"注册成功！",QMessageBox::Ok);
                emit sendRegistUser(regiUser);
                this->hide();
            }else{
                QMessageBox::warning(NULL, GAME_NAME, "两次输入的密码不一致，请重新输入！", QMessageBox::Ok);
            }

        }

}

void Regist::on_back_clicked()
{
    emit this->showMe(); //显示我界面
    this->hide(); //隐藏当前窗口
}

//初始化窗口
void Regist::initScene(){
    setWindowTitle(GAME_NAME); //设置窗口标题
    //    setWindowIcon(QIcon(GAME_ICON_)); //设置窗口图标
}

//判断两次输入的密码是否一致
bool Regist::isPwdSame()
{
    if(ui->pwd->text().compare(ui->surePwd->text()) == 0){ //如果密码一致
        return true;
    }else{
        return false;
    }
}

//判断端口是否存在
bool Regist::isPostExist(QString post)
{
    //存入postVec已有端口
    for(int i = 0; i < this->users.size(); i++){
        this->postVec.push_back(this->users.at(i)->post);
    }

    for(int i = 0; i < this->postVec.size(); i++){
        if(this->postVec[i].compare(post) == 0){
            return true;
        }
    }
    return false;
}

//显示当前窗口
void Regist::showRegist()
{
    //清空文本框中的内容
    ui->name->clear();
    ui->pwd->clear();
    ui->surePwd->clear();

    this->show(); //显示注册窗口
}
